package com.example.app.service;

import com.example.app.entity.Exercise;
import com.example.app.repository.ExerciseRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ExerciseService {

    private final ExerciseRepository exerciseRepository;

    public List<Exercise> getExercisesByUserId(Long userId) {
        return exerciseRepository.findByUserId(userId);
    }

    public List<Exercise> getExercisesByUserIdAndDate(Long userId, LocalDate date) {
        return exerciseRepository.findByUserIdAndDate(userId, date);
    }

//    public Exercise saveExercise(Exercise exercise) {
//        return exerciseRepository.save(exercise);
//    }
    public Exercise saveExercise(Exercise exercise) {
        // 尝试查找已有记录
        Exercise existing = exerciseRepository.findByUserIdAndDateAndTime(
                exercise.getUserId(), exercise.getDate(), exercise.getTime());

        if (existing != null) {
            // 更新已有记录的其他字段
            existing.setContext(exercise.getContext());
            existing.setStartDate(exercise.getStartDate());
            existing.setEndDate(exercise.getEndDate());
            // 如有其他字段也一起更新
            return exerciseRepository.save(existing);
        } else {
            // 没有重复，新增
            return exerciseRepository.save(exercise);
        }
    }
    // ✅ 根据用户ID删除所有记录
    public void deleteByUserId(Long userId) {
        exerciseRepository.deleteByUserId(userId);
    }

    // ✅ 根据用户ID和日期删除记录
    public void deleteByUserIdAndDate(Long userId, LocalDate date) {
        exerciseRepository.deleteByUserIdAndDate(userId, date);
    }

    // ✅ 根据用户ID、日期和时间删除记录
    public void deleteByUserIdAndDateAndTime(Long userId, LocalDate date, LocalTime time) {
        exerciseRepository.deleteByUserIdAndDateAndTime(userId, date, time);
    }
}
